package com.artezio.testapp.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.artezio.testapp.domain.City;
import com.artezio.testapp.service.CityService;

@Controller
public class CityController {
	
	private static final Logger logger = LoggerFactory.getLogger(CityController.class);
	
	@Autowired
	private CityService cityService;

	@RequestMapping(value = {"/", "/city"}, method = RequestMethod.GET)
	public String shoHomePage(Model model) {
		
		List<City> cities = cityService.listCity();
		
		model.addAttribute("cities", cities);
		
		return "city";
	}
	
	@RequestMapping(value = "city/new")
	public String shoNewCity(Model model){
		logger.debug("Request for adding city");
		
		model.addAttribute("city", new City());
		return "edit-city";
	}
	
	@RequestMapping(value = "city/edit/{cityId}")
	public String shoEditCity(@PathVariable(value = "cityId") Integer cityId, Model model){
		logger.debug("Request for editing city");
		
		City city = cityService.getCity(cityId);
		
		model.addAttribute("city", city);
		
		return "edit-city";
	}
	
	@RequestMapping(value = "city/save")
	public String saveCity(City city, Model model){
		logger.debug("Request for saving city");
		
		cityService.addCity(city);
		
		return "redirect:/city";
	}
	
	@RequestMapping(value = "city/delete/{cityId}")
	public String removeCity(@PathVariable(value = "cityId") Integer cityId, Model model){
		logger.debug("Request for editing city");
		
		cityService.removeCity(cityId);
		
		return "redirect:/city";
	}
	
}
